/**
 * failure.js - 电机故障信息管理模块
 */

// API基本路径
const FAILURE_API_BASE = '/api/feibiao/failure';

// 保存当前页码和页面大小的变量
let currentFailurePage = 0;
let failurePageSize = 15;
let currentFailureSearchKeyword = '';

// 日期格式化
function formatFailureDateTime(date) {
    if (!date) return '--';
    try {
        const dateObj = new Date(date);
        if (isNaN(dateObj.getTime())) return '--';
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        const hours = String(dateObj.getHours()).padStart(2, '0');
        const minutes = String(dateObj.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (e) {
        return '--';
    }
}

function formatFailureNumber(num) {
    if (num === null || num === undefined) return '--';
    return parseFloat(num).toFixed(2);
}

// 加载故障信息列表
function loadFailureList(page = 0, size = 15) {
    currentFailurePage = page;
    failurePageSize = size;
    
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    let url = `${FAILURE_API_BASE}?page=${page}&size=${size}`;
    if (currentFailureSearchKeyword) {
        url += `&keyword=${encodeURIComponent(currentFailureSearchKeyword)}`;
    }
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                console.error('API请求失败:', response.status, response.statusText);
                return response.text().then(text => {
                    try {
                        // 尝试解析为JSON以获取更多错误信息
                        const errorData = JSON.parse(text);
                        console.error('错误详情 (JSON):', errorData);
                        if (errorData.message) {
                            throw new Error(`服务器错误 (${response.status}): ${errorData.message}`);
                        }
                    } catch (e) {
                        // 如果不是JSON或解析失败
                        console.error('错误详情 (Text):', text);
                    }
                    throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
                });
            }
            return response.json();
        })
        .then(data => {
            renderFailureTable(data);
        })
        .catch(error => {
            console.error('获取故障信息数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>尝试加载URL: ${url}</p>
                    <p>错误信息: ${error.message}</p>
                    <p>可能的原因:</p>
                    <ul>
                        <li>后端服务未启动或无法访问</li>
                        <li>数据库表结构与实体类不匹配</li>
                        <li>API路径配置不正确(当前路径: ${FAILURE_API_BASE})</li>
                        <li>后端逻辑出现异常</li>
                        <li>数据库连接问题</li>
                        <li>实体类与表结构字段不匹配</li>
                        <li>数据库权限不足</li>
                        <li>外键约束问题: 检查am_archives_base表中是否有电机记录</li>
                        <li>表名和实体类命名不一致</li>
                        <li>JPA配置问题</li>
                    </ul>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadFailureList()">重试</button>
                        <button class="btn btn-default" onclick="loadFeiBiaoContent('base')">返回电机基本信息</button>
                    </div>
                </div>
            `;
            showMessage('获取故障信息数据失败: ' + error.message, 'error');
        });
}

// 渲染故障信息表格
function renderFailureTable(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机故障信息管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showFailureForm()">新增</button>
            </div>
        </div>
        
        <div class="search-box">
            <input type="text" class="search-input" id="failureSearchInput" placeholder="输入电机ID搜索..." value="${currentFailureSearchKeyword}">
            <button class="search-btn" onclick="searchFailure()">搜索</button>
            ${currentFailureSearchKeyword ? '<button class="btn btn-default" onclick="clearFailureSearch()">返回列表</button>' : ''}
        </div>
        
        <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>电机ID</th>
                    <th>故障时间</th>
                    <th>故障类型</th>
                    <th>故障描述</th>
                    <th>故障原因</th>
                    <th>修复时间</th>
                    <th>修复措施</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.failureId || ''}</td>
                    <td>${item.motorId || ''}</td>
                    <td>${formatFailureDateTime(item.failureTime)}</td>
                    <td>${item.failureType || ''}</td>
                    <td>${item.failureDescription || ''}</td>
                    <td>${item.failureCause || ''}</td>
                    <td>${formatFailureDateTime(item.repairTime)}</td>
                    <td>${item.repairMeasures || ''}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewFailure(${item.failureId})">查看</a>
                        <a href="javascript:void(0)" onclick="editFailure(${item.failureId})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteFailure(${item.failureId})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += `<tr><td colspan="9" class="text-center">暂无数据</td></tr>`;
    }
    html += `</tbody></table></div>`;
    
    // 添加分页控件
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${currentFailurePage <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentFailurePage <= 0 ? 'void(0)' : 'loadFailureList(' + (currentFailurePage - 1) + ', ' + failurePageSize + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === currentFailurePage) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadFailureList(${i}, ${failurePageSize})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${currentFailurePage >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${currentFailurePage >= data.totalPages - 1 ? 'void(0)' : 'loadFailureList(' + (currentFailurePage + 1) + ', ' + failurePageSize + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    mainContent.innerHTML = html;
}

// 清除搜索
function clearFailureSearch() {
    currentFailureSearchKeyword = '';
    currentFailurePage = 0;
    loadFailureList(0, failurePageSize);
}

// 跳转到指定页
function gotoFailurePage(page) {
    loadFailureList(page, failurePageSize);
}

// 搜索故障信息
function searchFailure() {
    const keyword = document.getElementById('failureSearchInput').value.trim();
    currentFailureSearchKeyword = keyword;
    currentFailurePage = 0;
    
    if (!keyword) {
        loadFailureList(0, failurePageSize);
        return;
    }
    
    // 直接使用备用搜索方法，因为后端没有实现通用搜索接口
    fallbackSearch(keyword);
}

// 备用搜索方法（使用两个单独的端点）
function fallbackSearch(keyword) {
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 先按电机ID查找
    fetch(`${FAILURE_API_BASE}/by-motor?motorId=${encodeURIComponent(keyword)}`)
        .then(response => {
            if (response.ok) return response.json();
            // 如果不是电机ID，再按故障类型查找
            return fetch(`${FAILURE_API_BASE}/by-type?failureType=${encodeURIComponent(keyword)}`)
                .then(r2 => r2.ok ? r2.json() : []);
        })
        .then(data => {
            // 将结果转换为分页格式
            const pageData = {
                content: Array.isArray(data) ? data : [],
                totalPages: 1,
                number: 0,
                size: Array.isArray(data) ? data.length : 0,
                first: true,
                last: true,
                totalElements: Array.isArray(data) ? data.length : 0
            };
            renderFailureTable(pageData);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
            // 如果搜索也失败，返回空结果
            renderFailureTable({
                content: [],
                totalPages: 0,
                number: 0,
                size: failurePageSize,
                first: true,
                last: true,
                totalElements: 0
            });
        });
}

// 显示新增/编辑表单
function showFailureForm(data = null) {
    const isEdit = !!data;
    const mainContent = document.getElementById('mainContent');
    const formTitle = isEdit ? '编辑故障信息' : '新增故障信息';
    const submitButtonText = isEdit ? '更新' : '保存';
    let failureTimeValue = '';
    let repairTimeValue = '';
    if (isEdit && data.failureTime) {
        const date = new Date(data.failureTime);
        failureTimeValue = date.toISOString().slice(0, 16);
    }
    if (isEdit && data.repairTime) {
        const date = new Date(data.repairTime);
        repairTimeValue = date.toISOString().slice(0, 16);
    }
    let html = `
        <div class="content-header">
            <h2 class="content-title">${formTitle}</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadFailureList(${currentFailurePage}, ${failurePageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="form-container">
        <form id="failureForm" class="data-form" onsubmit="event.preventDefault(); saveFailure(this, ${isEdit});">
            ${isEdit ? `<input type="hidden" name="failureId" value="${data.failureId}">` : ''}
            <div class="form-group">
                <label for="motorId">电机ID</label>
                <input type="text" id="motorId" name="motorId" class="form-control" value="${isEdit ? data.motorId : ''}" required>
            </div>
            <div class="form-group">
                <label for="failureTime">故障时间</label>
                <input type="datetime-local" id="failureTime" name="failureTime" class="form-control" value="${failureTimeValue}" required>
            </div>
            <div class="form-group">
                <label for="failureType">故障类型</label>
                <input type="text" id="failureType" name="failureType" class="form-control" value="${isEdit ? data.failureType : ''}" required>
            </div>
            <div class="form-group">
                <label for="failureDescription">故障描述</label>
                <textarea id="failureDescription" name="failureDescription" class="form-control" required>${isEdit ? data.failureDescription : ''}</textarea>
            </div>
            <div class="form-group">
                <label for="failureCause">故障原因</label>
                <input type="text" id="failureCause" name="failureCause" class="form-control" value="${isEdit ? data.failureCause : ''}" required>
            </div>
            <div class="form-group">
                <label for="repairTime">修复时间</label>
                <input type="datetime-local" id="repairTime" name="repairTime" class="form-control" value="${repairTimeValue}">
            </div>
            <div class="form-group">
                <label for="repairMeasures">修复措施</label>
                <textarea id="repairMeasures" name="repairMeasures" class="form-control">${isEdit ? data.repairMeasures : ''}</textarea>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">${submitButtonText}</button>
                <button type="button" class="btn btn-default" onclick="loadFailureList(${currentFailurePage}, ${failurePageSize})">取消</button>
            </div>
        </form>
        </div>
    `;
    mainContent.innerHTML = html;
}

// 保存故障信息
function saveFailure(form, isEdit) {
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });
    if (data.failureTime) data.failureTime = new Date(data.failureTime).toISOString();
    if (data.repairTime) data.repairTime = new Date(data.repairTime).toISOString();
    const url = isEdit ? `${FAILURE_API_BASE}/${data.failureId}` : FAILURE_API_BASE;
    const method = isEdit ? 'PUT' : 'POST';
    fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) throw new Error('网络响应错误');
        return response.json();
    })
    .then(() => {
        showMessage(`${isEdit ? '更新' : '创建'}故障信息成功`, 'success');
        loadFailureList(currentFailurePage, failurePageSize);
    })
    .catch(error => {
        showMessage(`${isEdit ? '更新' : '创建'}失败: ` + error.message, 'error');
    });
}

// 查看故障详情
function viewFailure(failureId) {
    fetch(`${FAILURE_API_BASE}/${failureId}`)
        .then(response => {
            if (!response.ok) throw new Error('网络响应错误');
            return response.json();
        })
        .then(data => {
            showFailureDetail(data);
        })
        .catch(error => {
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

// 显示故障详情
function showFailureDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">故障信息详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadFailureList(${currentFailurePage}, ${failurePageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID</label><div class="detail-value">${data.failureId || '--'}</div></div>
            <div class="detail-group"><label>电机ID</label><div class="detail-value">${data.motorId || '--'}</div></div>
            <div class="detail-group"><label>故障时间</label><div class="detail-value">${formatFailureDateTime(data.failureTime) || '--'}</div></div>
            <div class="detail-group"><label>故障类型</label><div class="detail-value">${data.failureType || '--'}</div></div>
            <div class="detail-group"><label>故障描述</label><div class="detail-value">${data.failureDescription || '--'}</div></div>
            <div class="detail-group"><label>故障原因</label><div class="detail-value">${data.failureCause || '--'}</div></div>
            <div class="detail-group"><label>修复时间</label><div class="detail-value">${formatFailureDateTime(data.repairTime) || '--'}</div></div>
            <div class="detail-group"><label>修复措施</label><div class="detail-value">${data.repairMeasures || '--'}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editFailure(${data.failureId})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteFailure(${data.failureId})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadFailureList(${currentFailurePage}, ${failurePageSize})"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

// 编辑故障信息
function editFailure(failureId) {
    fetch(`${FAILURE_API_BASE}/${failureId}`)
        .then(response => {
            if (!response.ok) throw new Error('网络响应错误');
            return response.json();
        })
        .then(data => {
            showFailureForm(data);
        })
        .catch(error => {
            showMessage('获取编辑信息失败: ' + error.message, 'error');
        });
}

// 删除故障信息
function deleteFailure(failureId) {
    if (!confirm('确定要删除此故障信息吗？此操作不可恢复。')) return;
    fetch(`${FAILURE_API_BASE}/${failureId}`, { method: 'DELETE' })
        .then(response => {
            if (!response.ok) throw new Error('网络响应错误');
            showMessage('删除故障信息成功', 'success');
            loadFailureList(currentFailurePage, failurePageSize);
        })
        .catch(error => {
            showMessage('删除失败: ' + error.message, 'error');
        });
}

// 全局导出
if (typeof window !== 'undefined') {
    window.loadFailureList = loadFailureList;
    window.renderFailureTable = renderFailureTable;
    window.searchFailure = searchFailure;
    window.clearFailureSearch = clearFailureSearch;
    window.gotoFailurePage = gotoFailurePage;
    window.fallbackSearch = fallbackSearch;
    window.showFailureForm = showFailureForm;
    window.saveFailure = saveFailure;
    window.viewFailure = viewFailure;
    window.showFailureDetail = showFailureDetail;
    window.editFailure = editFailure;
    window.deleteFailure = deleteFailure;
    window.formatFailureDateTime = formatFailureDateTime;
    window.formatFailureNumber = formatFailureNumber;
} 